package com.vtech.ont.inference.impl;

import com.vtech.ont.inference.RuleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.jena.reasoner.rulesys.Rule;
import org.apache.jena.util.FileUtils;
import org.egc.commons.exception.BusinessException;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author houzhiwei
 * @date 2017/6/29 14:03
 */
@Slf4j
@Service
public class RuleServiceImpl implements RuleService {
    @Override
    public List<Rule> parseStringRules(String rulesStr)
    {
        List<Rule> rules = null;
        InputStream in = new ByteArrayInputStream(rulesStr.getBytes());
        BufferedReader br = new BufferedReader(FileUtils.asBufferedUTF8(in));
        rules = Rule.parseRules(Rule.rulesParserFromReader(br));
        return rules;
    }

    @Override
    public List<Rule> parseRules(String ruleFilePath)
    {
        List<Rule> rules = new ArrayList<Rule>();
        try {
            URL in = this.getClass().getResource(ruleFilePath);
            // 读取规则文件
            BufferedReader br = new BufferedReader(new FileReader(in.getFile()));
            // 获取规则
            rules = Rule.parseRules(Rule.rulesParserFromReader(br));
            return rules;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getLocalizedMessage());
            throw new BusinessException(e, "Parse rule file failed.");
        }
    }
}
